import Taro from "@tarojs/taro";
import apiConfig from "./apiConfig";
import { httpUrlAddKey } from "@/utils/tools";
//网络请求拦截器
const interceptor = function (chain) {
  const requestParams = chain.requestParams;
  const { method, data, url } = requestParams;
  let token = Taro.getStorageSync("Token"); //拿到本地缓存中存的token
  requestParams.header = {
    ...requestParams.header,
    Authorization: token, //将token添加到头部
  };
  console.log(
    "网络请求参数如下",
    "Url:",
    url,
    "Data:",
    data,
    "请求方式:",
    method
  );
  return chain.proceed(requestParams).then((res) => {
    // console.log('resresres',res);
    // if(res.data.code !== 0){//xhq阻止出错也能走then函数
    //   //message

    //     Taro.showToast({
    //       title:res.data.message || '出错了,请稍后再试',
    //       icon: 'error',
    //       duration: 2000
    //     })

    //   // throw Error('')
    // }else{
    //   return res;
    // }
    return res;
   
  });
};
// 拦截器添加Token
Taro.addInterceptor(interceptor);

const request = async (method, url, params) => {
  //由于post请求时习惯性query参数使用params，body参数使用data，而taro只有data参数，使用contentType作为区分，因此此处需要做一个判断
  let contentType = params?.data
    ? "application/json"
    : "application/x-www-form-urlencoded";
  if (params) contentType = params?.headers?.contentType || contentType;
  const option = {
    method,
    isShowLoading: false,
    url: apiConfig.baseUrl + url,
    data: params && (params?.data || params?.params),
    header: {
      "content-type": contentType,
    },
    success(res) {
    console.log('resresres1',res);

      //  根据状态值处理请求
      switch (res?.statusCode) {
        case 503: {
          break;
        }
        default:
        
          break;
      }
    },
    error(e) {
      console.log("api", "请求接口出现问题", e);
    },
  };
  console.log(option);
  const resp = await Taro.request(option);
  return resp.data; //根据个人需要返回
};

export default {
  get: (url, config) => {
    return request("GET", url, config);
  },
  post: (url, config, params?) => {
    if (params !== undefined) {
      // Post请求URL自动添加参数
      Object.keys(params).forEach((key) => {
        url = httpUrlAddKey(url, key, params[key]);
      });
    }
    console.log("--", config);
    return request("POST", url, config);
  },
  put: (url, config) => {
    return request("PUT", url, config);
  },
  delete: (url, config) => {
    return request("DELETE", url, config);
  },
  patch: (url, config) => {
    return request("PATCH", url, config);
  },
};
